﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.EntityClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FaWorks.WebSite.Controllers.Model
{
    public class KnowledgeTypeController : Controller
    {
        public ActionResult GetIDByName(string typeName) {
            Models.AjaxResult ar = new Models.AjaxResult();
            var model = KlDB.KnowledgeTypes.FirstOrDefault<Models.Knowledge.KnowledgeType>(m => m.Name == typeName);
            if (model == null)
            {
                ar.Success = false;
            }
            else {
                ar.Data = model.id;
            }

            return Json(ar, JsonRequestBehavior.AllowGet);
        }

        [ActionName("CURD"), HttpGet]
        public ActionResult Read(int? id)
        {
            return Json(KlDB.KnowledgeTypes, JsonRequestBehavior.AllowGet);
        }

        [ActionName("CURD"), HttpPost]
        public ActionResult Create(Models.Knowledge.KnowledgeType knowledgeType)
        {
            Models.AjaxResult ar = new Models.AjaxResult();
            try {
                KlDB.KnowledgeTypes.Add(knowledgeType);
                KlDB.SaveChanges();

                //Hubs.UserHub.Instance.Clients.All.Create(knowledgeType);
            }
            catch (Exception ex) {
                ar.Success = false;
                ar.Data = ex.Message;
            }

            ar.Data = knowledgeType.id;
            return Json(ar);
        }

        [ActionName("CURD"), HttpPut]
        public ActionResult Update(Int32 id, Models.Knowledge.KnowledgeType knowledgeType)
        {
            Models.AjaxResult ar = new Models.AjaxResult();
            try
            {
                var curKnowledgeType = KlDB.KnowledgeTypes.Find(id);
                curKnowledgeType.Name = knowledgeType.Name;
                KlDB.SaveChanges();

                //Hubs.UserHub.Instance.Clients.All.Update(curKnowledgeType);
            }
            catch (Exception ex)
            {
                ar.Success = false;
                ar.Data = ex.Message;
            }

            ar.Data = knowledgeType.id;
            return Json(ar);
        }

        [ActionName("CURD"), HttpDelete]
        public ActionResult Delete(int id) {
            Models.AjaxResult ar = new Models.AjaxResult();
            try
            {
                var curUser = KlDB.KnowledgeTypes.Find(id);
                KlDB.KnowledgeTypes.Remove(curUser);
                KlDB.SaveChanges();

                //Hubs.UserHub.Instance.Clients.All.Delete(curUser);
            }
            catch (Exception ex)
            {
                ar.Success = false;
                ar.Data = ex.Message;
            }

            return Json(ar);
        }


        private KlDataBase KlDB = new KlDataBase();

    }
}
